package com.balloon.springboot.datasource.aop;

import com.balloon.springboot.datasource.datasourceholder.DataSourceContextHolder;
import com.balloon.springboot.datasource.prorperties.LocalDataSourceProperties;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.HashSet;


/**
 * 多数据源切面
 *
 * @author liaofuxing
 * @data 2021/9/18
 */
@Aspect
@EnableConfigurationProperties(LocalDataSourceProperties.class)
@Configuration
public class DataSourceAspect {

    private static final Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    @Autowired
    private LocalDataSourceProperties localDataSourceProperties;

    @Pointcut("@annotation(DataSourceRouteKey)")
    public void pointCut() {

    }

    @Before("pointCut() && @annotation(dataSourceRouteKey)")
    public void doBefore(DataSourceRouteKey dataSourceRouteKey) throws Exception {
        HashSet<String> dataSourceSet = DataSourceContextHolder.getDataSourceSet();

        if (localDataSourceProperties.getConf().getUseDefaultDatasource() && dataSourceSet.contains(dataSourceRouteKey.type())) {
            log.info("当前正在使用[{}]数据源", dataSourceRouteKey.type());
            DataSourceContextHolder.setDataSourceHolder(dataSourceRouteKey.type());
        } else if (!localDataSourceProperties.getConf().getUseDefaultDatasource() && dataSourceSet.contains(dataSourceRouteKey.type())) {
            log.info("当前正在使用[{}]数据源", dataSourceRouteKey.type());
            DataSourceContextHolder.setDataSourceHolder(dataSourceRouteKey.type());
        } else if (!localDataSourceProperties.getConf().getUseDefaultDatasource() && !dataSourceSet.contains(dataSourceRouteKey.type())) {
            log.info("当前正在使用[{}]数据源", dataSourceRouteKey.type());
            throw new SQLException("没有找到可用数据源,并且不允许使用默认数据源,若想使用请在配置文件db.conf.use-default-datasource中开启");
        } else if (localDataSourceProperties.getConf().getUseDefaultDatasource() && !dataSourceSet.contains(dataSourceRouteKey.type())) {
            log.warn("没有找到可用数据源,当前正在使用默认数据源,若不想在没有找到数据源的情况下使用默认数据源操作,请在配置文件db.conf.use-default-datasource中关闭");
            DataSourceContextHolder.setDataSourceHolder(dataSourceRouteKey.type());
        }
    }

    @After("pointCut()")
    public void doAfter() {
        DataSourceContextHolder.clear();
    }

}